package com.pactera.utils;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TreeUtils {

    private TreeUtils() {
    }

    /**
     * [节点唯一标识]字段 EC_liqingdian
     */
    private static final String GUID = "guid";
    /**
     * [唯一标识全路径]字段 EC_liqingdian
     */
    private static final String GUID_FULL_PATH = "fullGuid";
    /**
     * [文本名称]字段 EC_liqingdian
     */
    private static final String TEXT = "text";
    /**
     * [文本名称全路径]字段 EC_liqingdian
     */
    private static final String NAME_FULL_PATH = "fullName";
    /**
     * [父节点标识]字段 EC_liqingdian
     */
    private static final String PARENT = "parent";
    /**
     * 全路径拼接父 EC_liqingdian
     */
    private static final String SEPARATOR = "/";

    /**
     * 计算树节点的全路径
     *
     * @param list 节点全集
     * @param root 根节点标识值
     * @author: liqingdian
     */
    public static void fullPath(List<Map<String, String>> list, final String root) {
        if (CollectionUtils.isNotEmpty(list)) {
            // 获取根节点
            List<Map<String, String>> roots = list.stream().filter(a -> StringUtils.equals(root, a.get(PARENT))).collect(Collectors.toList());
            // 创建子孙节点容器
            List<Map<String, String>> childrens = new ArrayList<>(list);
            // 遍历递归生成全路径
            for (Map<String, String> map : roots) {
                map.put(GUID_FULL_PATH, SEPARATOR + map.get(GUID));
                map.put(NAME_FULL_PATH, SEPARATOR + map.get(TEXT));
                recursion(map, childrens);
            }
        }
    }

    /**
     * 递归算法
     *
     * @author: EC_liqingdian
     * @Modify:
     * @Date: 2019/12/18
     */
    private static void recursion(final Map<String, String> parent, List<Map<String, String>> computes) {
        // 获取当前parent的子节点
        List<Map<String, String>> children = computes.stream().filter(
                a -> StringUtils.equals(parent.get(GUID), a.get(PARENT))
        ).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(children)) {
            return;
        }
        // 容器删除这些子节点，减少下次遍历次数
        computes.removeAll(children);
        // 全路径
        StringBuilder guidFullPath;
        StringBuilder nameFullPath;
        for (Map<String, String> child : children) {
            guidFullPath = new StringBuilder();
            guidFullPath.append(parent.get(GUID_FULL_PATH));
            guidFullPath.append(SEPARATOR);
            guidFullPath.append(child.get(GUID));
            child.put(GUID_FULL_PATH, guidFullPath.toString());

            nameFullPath = new StringBuilder();
            nameFullPath.append(parent.get(NAME_FULL_PATH));
            nameFullPath.append(SEPARATOR);
            nameFullPath.append(child.get(TEXT));
            child.put(NAME_FULL_PATH, nameFullPath.toString());
            recursion(child, computes);
        }
    }
}
